<script setup lang="ts">
import { InputPassword } from '~comp/input';
import Turnstile, { cfRules } from '~comp/Turnstile.vue';
import { flzxsqc } from '~/utils';
import { useFirstTimeRewardsState } from '../hooks';
import { useLoginApiMethods } from './third-party/useLoginApiMethods';

const props = defineProps<{
  email?: string;
  onToSignUp?: () => void;
  onToForgetPassword?: () => void;
  onFulfilled?: () => void;
}>();

const appStore = useAppStore();

const form = useAntdForm({
  email: {
    value: props.email ?? '',
    rules: [{ required: true, type: 'email', message: $t('aw95tLwTkGmrgSVCHW') }],
  },
  password: {
    value: '',
    rules: [{ required: true, message: $t('mfFbQx6d5lMlEhlQg5eV') }],
  },
  cf_turnstile_response: {
    value: '',
    rules: cfRules,
  },
});

const { getLoadingRef, emailLogin } = useLoginApiMethods();
const turnstileDomRef = ref();

function submit() {
  emailLogin({ ...form.state, password: flzxsqc(form.state.password), is_luckyspin: useFirstTimeRewardsState() }, props.onFulfilled, (err) => {
    if (err.code !== 15028 || !globalPopups.verify2FA.modalProps.open) {
      turnstileDomRef.value?.reset?.();
      form.$form?.clearValidate?.();
    }
  });
}
</script>

<template>
  <div>
    <AForm v-bind="form.props" class="ant-cover__Form-compact" :disabled="getLoadingRef" @finish="submit()">
      <TAntdTheme component="Input" theme="light">
        <AFormItem v-bind="form.itemProps.email">
          <AInput v-model:value="form.state.email" :placeholder="$t('hVaEobWzd70kjGP9Awnt')" allowClear>
            <template #prefix>
              <i class="i-ri:mail-fill mr-1 text-1.2em text-sys-text-body" />
            </template>
          </AInput>
        </AFormItem>
        <AFormItem v-bind="form.itemProps.password">
          <InputPassword v-model:value="form.state.password" :placeholder="$t('j0xjWyPV3Op0WcKas3Ke')" />
        </AFormItem>
        <AFormItem v-bind="form.itemProps.cf_turnstile_response">
          <Turnstile ref="turnstileDomRef" v-model:value="form.state.cf_turnstile_response" />
        </AFormItem>
      </TAntdTheme>
      <div
        class="my-3 ml-auto w-fit cursor-pointer text-sys-text-body hover:(text-sys-text-head underline)"
        @click="onToForgetPassword?.()"
      >
        {{ $t('dj49WxBeDn3fRqBjRrqaB') }}
      </div>
      <AButton
        class="ant-cover__Button-3d-primary !w-full"
        htmlType="submit"
        type="primary"
        :loading="getLoadingRef"
        :disabled="getLoadingRef"
      >
        {{ $t('qwZi820O3qWpsae62Juc') }}
      </AButton>
    </AForm>

    <div class="my-2 text-center">
      <I18nT keypath="pkKo6iqCzNtnoUauGiDY">
        <template #name>
          {{ appStore.appName }}
        </template>
      </I18nT>
      <span class="cursor-pointer url-yellow-underline" @click="onToSignUp?.()">{{ $t('jeo82MixWd5yf5SzCgHt') }}</span>
    </div>
  </div>
</template>
